import {Component} from "@angular/core";
import {Router, ActivatedRoute} from "@angular/router";
import {AwardService} from "../svrs/award.service";
import {UserInfo} from "../svrs/domain";

@Component({
  selector: 'zm-prize',
  templateUrl: './prize.component.html',
  styleUrls: ['./prize.component.css']
})

export class PrizeComponent {
  prize;
  current;
  userInfos: UserInfo[];
  luckUsers: UserInfo[] = [];
  awardCount:number = 5;
  constructor (private svr:AwardService,
               private aRouter:ActivatedRoute,
               private router:Router) {
    this.aRouter.params.subscribe(pars=>{
      if(pars && pars["id"]){
         svr.prize(pars["id"]).subscribe(data=>{
           this.prize=data;
           svr.infos(this.prize.award.id).subscribe(data1=>{
             svr.users(data1["map"](info=>info.openId)).subscribe(
               (data2:any)=>{
                 this.userInfos=data2;
                 if(this.userInfos && this.userInfos.length>=5){
                   this.current=1;
                 }
               }
             );
           });
         });
      }
    })
  }
  interval;
  start(){
    if (this.luckUsers.length === this.awardCount) {
      return;
    }
    if(this.interval) {
      this.stop();
      return;
    }
    if(this.userInfos && this.userInfos.length<5) return;
    this.current=1;
    this.winner=null;
    this.interval=setInterval(()=>{
      if(this.current>=this.userInfos.length-2){
        this.current=1;
      }else{
        this.current++;
      }
    },300);
  }
  winner;
  stop() {
    this.svr.annoucePrize(this.prize.id,true)
      .subscribe(data=>{
        this.winner=data;
        this.svr.users([data["openId"]]).subscribe(
          data1=>{
            this.winner=data1[0];
            this.luckUsers.push(this.winner);
            clearInterval(this.interval);
            delete this.interval;
            this.current=1;
          }
        );
      });
  }

  navBackUp() {
    this.router.navigateByUrl("/");
  }
}
